# Tests client ability to log in and register an account on a server.

import time

import flexitest

C0_USERNAME = "fooclient"
C0_PASSWORD = "fcpassword"

C1_USERNAME = "barclient"
C1_PASSWORD = "bcpassword"

@flexitest.register
class Test(flexitest.Test):
    def __init__(self, ctx: flexitest.InitContext):
        ctx.set_env("bare")

    def main(self, ctx: flexitest.RunContext):
        serv0 = ctx.get_service("serv0")
        client0 = ctx.get_service("client0")
        client1 = ctx.get_service("client1")
        time.sleep(1)

        c0rpc = client0.create_rpc()
        c1rpc = client1.create_rpc()

        # Check status.
        res = c0rpc.aspc_status()
        c0did = res["device_id"]
        print("c0 status", res)
        res = c1rpc.aspc_status()
        c1did = res["device_id"]
        print("c1 status", res)

        # Register both clients.
        s0addr = serv0.get_prop("p2p_addr")
        print("registering...")
        res = c0rpc.aspc_register(s0addr, C0_USERNAME, C0_PASSWORD)
        print("register c0", res)
        res = c1rpc.aspc_register(s0addr, C1_USERNAME, C1_PASSWORD)
        print("register c1", res)

        # Now see if they can find each other.
        res = c0rpc.aspc_get_hs_user_devices(C1_USERNAME)
        print("query c0->c1", res)
        assert len(res) == 1, "wrong number of devices returned"
        assert res[0] == c1did, "unexpected device ID in result"
        res = c1rpc.aspc_get_hs_user_devices(C0_USERNAME)
        print("query c1->c0", res)
        assert len(res) == 1, "wrong number of devices returned"
        assert res[0] == c0did, "unexpected device ID in result"

        # Check status again.
        res = c0rpc.aspc_status()
        assert res["self_ref"] == C0_USERNAME, "wrong username reported in status"
        print("c0 status", res)
        res = c1rpc.aspc_status()
        print("c1 status", res)
        assert res["self_ref"] == C1_USERNAME, "wrong username reported in status"
